# work1和work2线程对全局变量的改变，随着数目的增大，开始异常。
# 原因：当多个任务在修改同一个资源，出现资源竞争


import time
import threading

# 定义全局变量
g_num = 0

# work1
def work1():
    # 声明g_num是一个全局变量，才能进行修改
    global g_num

    for i in range(1000000):
        g_num += 1
    print('work1--------',g_num)  

# work2
def work2():
    # 声明g_num是一个全局变量，才能进行修改
    global g_num

    for i in range(1000000):
        g_num += 1
    print('work2--------',g_num)  

if __name__=='__main__':
    # 创建2个线程
    t1 = threading.Thread(target=work1)
    t2 = threading.Thread(target=work2)
    # 启动线程
    t1.start()
    # 优先让t1线程优先执行，t1执行完毕后，t2才能执行
    t1.join()
    t2.start()

    # 子线程都执行完之后 才打印g_num
    while len(threading.enumerate()) !=1:
        time.sleep(0.5)

    # 在t1和t2 线程执行完成后打印g_num
    print('g_num---------',g_num)

